package com.gui.juc.cas;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.Consumer;
import java.util.function.Supplier;

@Slf4j

public class LongAdderDemo {


    public static void main(String[] args) {

        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 10; i++) {
            test(threadPool, () -> new AtomicInteger(0), AtomicInteger::incrementAndGet, "AtomicInteger");
            test(threadPool, LongAdder::new, LongAdder::increment, "LongAdder");
        }

        threadPool.shutdown();

    }

    private static <T> void test(ExecutorService threadPool, Supplier<T> supplier, Consumer<T> consumer, String type){
        long startTime = System.currentTimeMillis();

        T integer = supplier.get();

        CountDownLatch latch = new CountDownLatch(4);

        for (int i = 0; i < 4; i++) {
            threadPool.submit(() -> {
                for (int j = 0; j < 1000000; j++) {
                    consumer.accept(integer);
                }
                latch.countDown();
            });
        }

        try {
            latch.await();
        }catch (Exception e) {
            log.error("error");
        }
        log.debug("{}: 最终结果为：{},花费时间：{}", type, integer, (System.currentTimeMillis() - startTime));

    }
}
